import Request from '@/common/utils/request.js';
import config from '@/uni.config.js';
import { showModal } from '@/common/hooks/useShow.js';
/**
 * 上传图片文件
 * @param {Array} files 上传的文件数据[{fileUrl:XXX}]
 */
export function uploadImg(files) {
	let url = config.host.upload + '/app/upload/image',
		header = {},
		count = 0,
		returnFiles = [];
	header['Content-Type'] = 'multipart/form-data';
	uni.showLoading({
		mask: true,
		title: '上传中'
	});
	return new Promise((resolve, reject) => {
		for (let i = 0; i < files.length; i++) {
			uni.uploadFile({
				url,
				header,
				filePath: files[i].fileUrl,
				name: 'file',
				success: (res) => {
					let resData = JSON.parse(res.data);
					if (resData.code == 200) {
						returnFiles.push({
							type: files[i].type,
							...resData.data
						});
					} else if (resData.code != 200) {
						uni.showToast({
							icon: 'none',
							mask: true,
							title: resData.message
						})
						reject(resData);
					}
				},
				fail: (res) => {
					uni.showToast({
						icon: 'none',
						title: '上传失败'
					});
					reject(res);
				},
				complete() {
					count++;
					if (count == files.length) {
						uni.hideLoading();
						if (returnFiles.length > 0) {
							resolve(returnFiles);
						} else {
							showModal({
								content: '文件上传成功个数为0，请上传有效的文件',
								showCancel: false
							})
							reject(false);
						}
					}
				}
			})
		}
	})
}
// 使用案例
// uni.chooseImage({
// 	count: 1,
// 	crop: {
// 		width: 600,
// 		height: 600
// 	},
// 	success(res) {
// 		const size = (+res.tempFiles[0].size / 1024 / 1024);
// 		if (size > 2) {
// 			showModal({
// 				content: '建议上传小于2M尺寸为100*100的图片',
// 				showCancel: false
// 			})
// 		} else {
// 			let data = [{
// 				type: 'head',
// 				fileUrl: res.tempFiles[0].path
// 			}]
// 			uploadImg(data).then(uploadRes => {
// 				console.log('uploadRes', uploadRes)
// 			}).catch(error => {});
// 		}
// 	}
// })
